package Information_sysyem_jdbc.Utiles;

import com.alibaba.druid.pool.DruidDataSourceFactory;
import javax.sql.DataSource;
import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

/**
 * @author LiangHaiBo
 * @version 1.0
 * @date 2021.8.21 上午 9:31
 */
public class JdbcUtils {
    private static DataSource ds;
    private static ThreadLocal<Connection> t1 = new ThreadLocal<>();


    //构造方法私有化
    private JdbcUtils() {
    }
    //静态代码块
    static {
        try {
            Properties prop = new Properties();
            InputStream inputStream = JdbcUtils.class.getClassLoader().getResourceAsStream("DruidJdbc.properties");
            prop.load(inputStream);
            ds = DruidDataSourceFactory.createDataSource(prop);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //提供静态方法,单独获取数据源
    public static DataSource getDataSourse() {
        return ds;
    }

    //获取连接对象Connection静态功能
    public static Connection getConnection() {
        Connection conn = null;
        try {
            conn = t1.get();
            if (conn == null) {
                conn = ds.getConnection();
                t1.set(conn);
            }
            return conn;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    //关闭(释放资源)资源
    public static void close(ResultSet rs, Statement stmt, Connection conn) {
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (stmt != null) {
            try {
                stmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (conn != null) {
            try {
                conn.close();
                //关闭之后,归还到连接池中,需要从当前线程中解绑
                t1.remove();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    public static void close(Statement stmt, Connection conn) {
        close(null, stmt, conn);
    }
}
